//
//  LYCommentController.m
//  LYLiveApp
//
//  Created by QD on 16/8/25.
//  Copyright © 2016年 览益信息科技. All rights reserved.
//

#import "LYCommentController.h"
#import "LYVideoContainerCell.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "LYCommentModel.h"
#import "LYFullCommentNewCell.h"
#import "LYVideoCommentNewCell.h"

NSString *const LYCommentControllerInputBgHidden = @"LYCommentControllerInputBgHidden";

@interface LYCommentController ()
<UITableViewDelegate,
UITableViewDataSource,
RequestDelegate,
UIScrollViewDelegate
>
@property (nonatomic,strong) UIView *inputBg;
@property (nonatomic,strong) NSTimer *commentTimer;
@property (weak, nonatomic) IBOutlet UIButton *latestMessageBtn;
@property(nonatomic,assign) BOOL isInBottom;
@property(nonatomic,strong) NSTimer *refreshTimer;
@property(nonatomic,strong) NSMutableArray *dataArrays;
@property(nonatomic,strong) NSMutableArray *addLatestArrays;

@end

@implementation LYCommentController

#pragma mark ----- life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    self.isInBottom = NO;
    self.commentTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(_loadOldData)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webSocketDataUpdate:) name:kWebSocketDataUpdate object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground) name:kApplicationDidEnterBackground object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForeground) name:kApplicationDidEnterForeground object:nil];
}

- (void)appEnterBackground {
    
    [self _stopRefreshTimer];    
}

- (void)appEnterForeground {
   
    [self _addRefreshTimer];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
   
}

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated];
    [self _addRefreshTimer];
   
    [LYLocalData sharedInstance].roomInfo.id = @(0);
    
    WS(weakSelf)
    if (![LYUtil hasNetwork]) {
        [self.commentService getCommentInfoCacheCallBlock:^(BOOL success, NSMutableArray *object) {
            if (success) {
                weakSelf.dataArrays = object.mutableCopy;
                [weakSelf.commentTable reloadData];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (weakSelf.dataArrays.count) {
                        [weakSelf _scrollowAction];
                    }
                });
            }
        }];
    } else {
        NSDictionary *paraDic = @{@"roomId":@([LYLocalData sharedInstance].roomInfo.id.integerValue),
                                  @"num":@(20)};
        [self.commentService getCommentInfoWithParaDic:paraDic callBlock:^(BOOL success, NSMutableArray *object) {
           
            [LYUtil hideHUDTo:weakSelf.view];
            [weakSelf _endRefreshing];
            
            if (success) {
                weakSelf.dataArrays = [weakSelf _sortArray:object].mutableCopy;
                [weakSelf.commentTable reloadData];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (weakSelf.dataArrays.count) {
                        [weakSelf _scrollowAction];
                    }
                });
            } else {
                [LYUtil hideHUDTo:weakSelf.view];
                [weakSelf _endRefreshing];
            }
        }];
    }
}

- (void)_loadOldData {
    
    WS(weakSelf)
    if ([LYUtil hasNetwork]) {
        if (![LYUtil isNilOrEmpty:self.commentService.sinceKeyOld]) {
        // NSDictionary *paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[LYLocalData sharedInstance].roomInfo.id,@"roomId",@(20),@"num",self.commentService.sinceKeyOld,@"sinceKey", nil];
            NSDictionary *paraDic = @{@"roomId":@([LYLocalData sharedInstance].roomInfo.id.integerValue),
                                      @"num":@(20),
                                      @"sinceKey":self.commentService.sinceKeyOld,
                                      };
            [self.commentService getCommentOldInfoWithParaDic:paraDic callBlock:^(BOOL success, NSMutableArray *object) {
               
                [LYUtil hideHUDTo:weakSelf.view];
                [weakSelf _endRefreshing];
                if (success) {
                    [weakSelf.dataArrays addObjectsFromArray:object];
                    weakSelf.dataArrays = [weakSelf _sortArray:weakSelf.dataArrays];
                    [weakSelf.commentTable reloadData];
                }
            }];
        }
    } else {
        [self _endRefreshing];
    }
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self _stopRefreshTimer];
}

- (void)stopRefreshCommentTimer {
    
    [self _stopRefreshTimer];
}

- (void)beginRefreshCommentTimer {
    
    [self _addRefreshTimer];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)makeStatementWithId:(NSNumber *)toChatId content:(NSString *)content successBlock:(void (^)(BOOL success))successBlock {

    WS(weakSelf)
    if ([LYUtil hasNetwork])
    {
        
        NSString *contentString = [NSString stringWithFormat:@"览益...览益股市: %@",content];
        CGFloat lineHeight = [LYUtil sizeWithText:contentString
                                             font:[UIFont fontWithName:@"PingFangSC-Regular" size:15.0f]
                                            width:SCREEN_WIDTH - 24
                                      lineSpacing: 2].height + 10;
        
        NSDictionary *paraDic = @{@"roomId":@([LYLocalData sharedInstance].roomInfo.id.integerValue),
                                  @"content":content,
                                  @"toChatId":@(toChatId.integerValue)};
        [self.commentService stateMentActionParaDic:paraDic successBlock:successBlock callBlocl:^(BOOL success, LYCommentModel *model) {
         
            [weakSelf.dataArrays addObject:model];
            [weakSelf.commentTable reloadData];
            
            if (self.commentTable.contentSize.height > self.commentTable.frame.size.height) {
                
                CGPoint offsetY = CGPointMake(0, self.commentTable.contentSize.height - self.commentTable.frame.size.height + lineHeight);
                [self.commentTable setContentOffset:offsetY animated:NO];
            }
            
//            if (weakSelf.dataArrays.count) {
//                [weakSelf _scrollowAction];
//            }
        }];
    } else {
        [LYUtil showFailedHUD:@"提交失败，请稍后重试" AddedTo:self.view interval:2.0];
    }

}
#pragma mark ----- event response
- (IBAction)scrollowToTop:(id)sender {
    
    self.latestMessageBtn.hidden = YES;
    self.commentService.hasNewData = NO;
    [self.commentTable reloadData];
    
    [self _scrollowAction];
}

- (void)webSocketDataUpdate:(NSNotification *)notifycation {
    WS(weakSelf)
    NSDictionary *dataDic = notifycation.userInfo[@"feedsChat"];
    
    if ([dataDic isKindOfClass:[NSDictionary class]] && dataDic.count) {
        [self.commentService loadLatestData:dataDic callBlock:^(BOOL success, NSMutableArray *object) {
            if (success) {
                if (!weakSelf.addLatestArrays.count) {
                    weakSelf.addLatestArrays = @[].mutableCopy;
                }
                [weakSelf.addLatestArrays addObjectsFromArray:object.copy];
                if (weakSelf.commentService.hasNewData && !weakSelf.isInBottom && !weakSelf.isFullScrComment) {
                    weakSelf.latestMessageBtn.hidden = NO;
                } else {
                    weakSelf.latestMessageBtn.hidden = YES;
                }
            }
        }];
    }
}

#pragma mark ----- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat height = scrollView.frame.size.height;
    CGFloat contentOffsetY = scrollView.contentOffset.y;
    CGFloat bottomOffset = scrollView.contentSize.height - contentOffsetY;
    
    if (bottomOffset <= height + 225)
    {
        self.isInBottom = YES;
        self.latestMessageBtn.hidden = YES;
        self.commentService.hasNewData = NO;
    }
    else
    {
        self.isInBottom = NO;
    }
}

#pragma mark - RequestDelegate

-(void) eventRequestSuccess:(id)obj{
    
    [LYUtil hideHUDTo:self.view];
    
    [self _endRefreshing];
    [self.commentTable reloadData];
}

-(void) eventRequestError:(id)obj{
    
    [LYUtil hideHUDTo:self.view];
    [self _endRefreshing];
}


-(void)_endRefreshing
{
    if (self.commentTable.mj_header.isRefreshing) {
        [self.commentTable.mj_header endRefreshing];
    }
}

#pragma mark ----- private methods
- (void)_addRefreshTimer {
    
    [self _stopRefreshTimer];
    if (nil == _refreshTimer) {
         _refreshTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(_refreshData) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_refreshTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)_stopRefreshTimer {
    
    if (self.refreshTimer) {
        [self.refreshTimer invalidate];
        self.refreshTimer = nil;
    }
}

- (void)_refreshData {
    
    WS(weakSelf);
    if (self.addLatestArrays.count && self.isInBottom) {
        
        [self.dataArrays addObject:self.addLatestArrays[0]];
        [self.addLatestArrays removeObjectAtIndex:0];
//        self.dataArrays = [self _sortArray:self.dataArrays];
        [self.commentTable reloadData];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf _scrollowAction];
        });
    }
}

- (void)_scrollowAction {
   
    WS(weakSelf)
    if ([weakSelf.commentTable numberOfSections] > 0) {
        NSInteger lastSectionIndex = [weakSelf.commentTable numberOfSections] - 1;
        NSInteger lastRowIndex = [weakSelf.commentTable numberOfRowsInSection:lastSectionIndex] - 1;
        if (lastRowIndex > 0) {
            NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
            [weakSelf.commentTable scrollToRowAtIndexPath:lastIndexPath atScrollPosition: UITableViewScrollPositionBottom animated:YES];
        }
    }
}

- (NSMutableArray *)_sortArray:(NSMutableArray *)array {
    
    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] initWithCapacity:array.count];
    for (int i = 0; i < array.count; i ++) {
        LYCommentModel *model = array[i];
        [resultDict setObject:model forKey:[NSString stringWithFormat:@"%@",model.show.chatId]];
    }
    NSMutableArray *mutArray = [NSMutableArray arrayWithArray:resultDict.allValues];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"show.ctime" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sorter count:1];
    [mutArray sortUsingDescriptors:sortDescriptors];
    NSArray *reversedArray = [[mutArray reverseObjectEnumerator] allObjects];
    NSMutableArray *mutArrays = reversedArray.mutableCopy;
    return mutArrays;
}


#pragma mark - UITableViewDatasource && Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    if (self.dataArrays.count) {
        return self.dataArrays.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (self.isFullScrComment) {
        LYFullCommentNewCell *cell = [LYFullCommentNewCell cellWithTableView:tableView];
        if (self.dataArrays.count) {
            cell.commentModel = self.dataArrays[indexPath.row];
        }
        return cell;
    } else {
        
        LYVideoCommentNewCell *cell = [LYVideoCommentNewCell cellWithTableView:tableView];
        if (self.dataArrays.count) {
            cell.commentModel = self.dataArrays[indexPath.row];
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
       
    if (self.isFullScrComment) {
        LYCommentModel *model = self.dataArrays[indexPath.row];
        return [LYCommentModel returnHeightFullCommentNewWithModel:model];
    } else {
        LYCommentModel *model = self.dataArrays[indexPath.row];
        return [LYCommentModel returnHeightWithModel:model];
    }
    return 0;
}

#pragma mark ----- getters and setters
- (LYCommentService *)commentService {
   
    if (nil == _commentService) {
        _commentService = [[LYCommentService alloc] initWithDelegate:self];
    }
    return _commentService;
}
@end
